/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 文件操作
 * @author yuanguozheng
 */
var fs = require('fs');
var path = require('path');
var config = require('./config');
var urls = require('./urls');

/**
 * 建立基本的源码目录
 *
 * @return {Object} java和oc代码的输出路径
 */
function createBase() {
    var outPath = path.join(urls.getPath(config.projectConfig('path')), 'sources');
    var javaPath = path.join(outPath, 'java');
    var ocPath = path.join(outPath, 'oc');
    var csPath = path.join(outPath, 'cs');
    mkdirsSync(javaPath);
    mkdirsSync(ocPath);
    mkdirsSync(csPath);
    return {
        java: javaPath,
        oc: ocPath,
        cs: csPath
    };
}

/**
 * 创建文件夹
 *
 * @param {string} dir 路径
 * @param {string|number=} mode 权限
 * @return {boolean} 是否成功，成功返回true
 */
function mkdirsSync(dir, mode) {
    if (dir == null || dir === undefined || dir === '') {
        return false;
    }
    if (!fs.existsSync(dir)) {
        var tPath;
        dir.split(path.sep).forEach(function (dirName) {
            if (tPath) {
                tPath = path.join(tPath, dirName);
            }
            else {
                if (dirName !== '' && dirName !== null && dirName !== undefined) {
                    tPath = dirName;
                } else {
                    tPath = path.sep;
                }
            }
            if (!fs.existsSync(tPath)) {
                if (!fs.mkdirSync(tPath, mode)) {
                    return false;
                }
            }
        });
    }
    return true;
}

/**
 * 写入文件
 *
 * @param {string} baseDir 基本目录
 * @param {string} filename 文件名
 * @param {string} content 内容
 * @return {boolean} 是否成功，成功返回true
 */
function writeToFile(baseDir, filename, content) {
    if (baseDir == null || baseDir === undefined) {
        return false;
    }
    if (filename == null || filename === undefined || filename === '') {
        return false;
    }
    try {
        fs.writeFileSync(path.join(baseDir, filename), content);
        return true;
    } catch (e) {
        console.error('写入文件错误！文件名：' + filename);
        console.error(e);
        return false;
    }
}

module.exports = {
    mkdir: mkdirsSync,
    createBase: createBase,
    writeToFile: writeToFile
};